let startCount = 0;
let tourDateID;
let listData;
let mergeCells = [];
let hot;
//载入js表格库的css文件
window.main_API.injectStyle().then(res => {
    const injectStyle = document.createElement("link");
    injectStyle.type = "text/css";
    injectStyle.rel = "stylesheet";
    injectStyle.href = res;
    document.body.appendChild(injectStyle);
    injectStyle.onload = () => {
        //载入js表格库
        window.main_API.injectScript().then(res => {
            const injectScript = document.createElement("script");
            injectScript.src = res;
            document.body.appendChild(injectScript);
            injectScript.onload = () => {
                //载入js表格库的语言文件
                window.main_API.injectLanguageFile().then(res => {
                    const injectLanguage = document.createElement("script");
                    injectLanguage.type = "text/javascript";
                    injectLanguage.src = res;
                    document.body.appendChild(injectLanguage);
                    injectLanguage.onload = () => {
                        init();
                    }
                })
            }
        })
    }
})


async function init() {
    listData = await window.main_API.getListData();
    mergeCells = await window.main_API.getListData_merge();
    console.log('111');
    console.log(mergeCells);
    start();
    // console.log(listData);
    
}

function start() {

    document.getElementById("saveBtn").onclick = function () {
        window.main_API.saveListData(hot.getData(), mergeCells);
        window.main_API.changeTourDatesActualNum(hot.countRows()-hot.countEmptyRows(true)-1);
        setTimeout(function () {
            window.close();
        }, 1000);
    }

    hot = new Handsontable(document.getElementById("mainContainer"), {
        // configuration options, in the object literal notation
        licenseKey: "non-commercial-and-evaluation",
        data: listData,
        width: '100vw',
        height: '100vh',
        colHeaders: true,//显示列头
        rowHeaders: true,//显示行头
        customBorders: true,//显示边框
        dropdownMenu: true,//显示下拉菜单
        multiColumnSorting: true,//多列排序
        filters: true,//筛选器
        manualRowMove: true,//手动移动行
        language: 'zh-CN',//设置语言
        mergeCells: true,//合并单元格
        manualColumnFreeze: true,//手动冻结列
        manualColumnResize: true,//手动调整列宽
        className: ['htCenter', 'htMiddle'],//设置文本居中
        contextMenu: true,
        mergeCells: mergeCells,
        beforeOnCellContextMenu: function (event, coords, TD) {
            var colIndex = coords.col;
            var rowIndex = coords.row;
            var data = hot.getDataAtCell(rowIndex, colIndex);

            // 检查是否点击了特定列  
            if (colIndex === 5) { // 替换indexOfSpecialColumn为特定列的索引  
                // 显示自定义的右键菜单  
                hot.updateSettings({
                    contextMenu: {
                        items: {
                            "customItem": {
                                name: '定位',
                                callback: function (key, options) {
                                    // 在这里执行自定义操作
                                    // console.log(TD);
                                    console.log(coords);
                                    console.log(TD.getAttribute('rowspan'));
                                    console.log(data);
                                    TD.style.backgroundColor = 'green';
                                    if (TD.getAttribute('rowspan')==null) {
                                        return;
                                    }
                                    window.main_API.savePoiInfo(rowIndex,colIndex,TD.getAttribute('rowspan'),data);
                                    window.main_API.openMap();
                                }
                            },
                            '测试': {
                                name: '测试',
                                callback: function (key, options) {
                                    console.log(hot.getData());
                                    let nonEmptyRows = hot.countRows()-hot.countEmptyRows(true)-1;
                                    // console.log(nonEmptyRows);
                                }
                            }
                            ,
                            'mergeCells': {

                            },
                        },

                    }
                });
            } else {
                hot.updateSettings({
                    contextMenu: [
                        'row_above',
                        'row_below',
                        '---------',
                        'remove_row',
                        '---------',
                        '---------',
                        'mergeCells'
                    ]
                });
            }
        }
    });

    for (let i = 0; i < 50; i++) {
        hot.alter('insert_row_below');
    }

    hot.addHook('afterMergeCells', function (cellRange, mergeParent) {
        // console.log(cellRange, mergeParent);
        mergeCells.push(mergeParent);
    })

    // //插入新行后触发
    // hot.addHook('afterCreateRow', function (index, amount) {
    //     for (var i = 1; i < this.countRows()-1; i++) {
    //         this.setDataAtCell(i, 0, i); // 序号列是第一列，序号从1开始  
    //     }
    // });
    // //插入新行后触发
    // hot.addHook('afterRemoveRow', function (index, amount) {
    //     for (var i = 1; i < this.countRows()-1; i++) {
    //         this.setDataAtCell(i, 0, i); // 序号列是第一列，序号从1开始  
    //     }
    // });

    // hot.alter('insert_row_below');



}